<script setup>
  import { ref } from 'vue'
  // 1. 定义表单数据
  const formData = ref({
    mobile: '',
    password: '',
    alt: '关于我的描述',
  })
  // 2. 定义表单校验规则
  const formRules = {
    mobile: {
      rules: [
        { required: true, errorMessage: '请填写手机号码' },
        { pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号不正确' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入密码' },
        { pattern: /^[a-zA-Z0-9]{8}$/, errorMessage: '密码格式不正确' },
      ],
    },
  }
  // 3. 定义 ref 用于整体校验
  const formRef = ref()

  // 4. 提交表单
  const onSubmit = async () => {
    try {
      // 表单整体校验
      const res = await formRef.value.validate()
      console.log(res)
      uni.showToast({ title: '校验通过' })
    } catch {
      uni.showToast({ title: '校验失败', icon: 'error' })
    }
  }
</script>

<template>
  <view>
    <!-- 
          uni-forms         表单分区
            :model   绑定表单数据
            :rules   绑定校验规则
            ref      用于表单整体校验
          uni-forms-item    表单项
            name     绑定校验字段
          uni-easyinput     输入框
            v-model  双向绑定
        -->
    <uni-forms :model="formData" :rules="formRules" ref="formRef">
      <uni-forms-item name="mobile">
        <uni-easyinput
          type="text"
          :clearable="false"
          placeholder="请输入用户名"
          v-model="formData.mobile"
        ></uni-easyinput>
      </uni-forms-item>

      <uni-forms-item name="password">
        <uni-easyinput
          type="password"
          :clearable="false"
          placeholder="请输入密码"
          v-model="formData.password"
        ></uni-easyinput>
      </uni-forms-item>

      <uni-forms-item name="alt">
        <uni-easyinput
          type="textarea"
          :clearable="false"
          v-model="formData.alt"
          placeholder="请输入简介"
        ></uni-easyinput>
      </uni-forms-item>
      <button class="uni-button" type="primary" @click="onSubmit">提交</button>
    </uni-forms>
    {{ formData }}
  </view>
</template>

<style></style>
